<?php

namespace app\data\controller\api\auth;

use app\data\controller\api\Auth;
use think\facade\Cache;
use think\facade\Log;

/**
 * 车辆管理
 * Class CarInfo
 * @package app\data\controller\api\auth
 */
class CarInfo extends Auth
{
    /**
     * 绑定数据表
     * @var string
     */
    private $table = 'CarInfos';

    /**
     * 添加车辆
     * @throws \think\db\exception\DbException
     */
    public function set()
    {
        $data = $this->_vali([
            'uuid.value'       => $this->uuid,
            'id.default'     => 0,
            'fuel_type.require'    => '燃料类型不能为空！',
            'driving_image_1.require'    => '驾驶证正本不能为空！',
            'driving_image_2.require' => '驾驶证副本不能为空！',
            'plate_number.require' => '车牌号不能为空！',
            'vehicle_type.require' => '车辆类型不能为空！',
            'owner.require' => '所有人不能为空！',
            'use_character.require' => '使用性质不能为空！',
            'phone.require' => '联系电话不能为空！',
            'phone.mobile' => '手机号码格式错误！',
            'car_conditions.default' => [],
            'register_date.require' => '注册日期不能为空！',
            'other_info.default' => '',

            "overall_dimension.default" => '',
            "inspection_record.default" => '',
            "unladen_mass.default" => '',
            "file_number.default" => '',
            "traction_mass.default" => '',
            "gross_mass.default" => '',
            "approved_passenger_capacity.default" => '',
            "energy_type.default" => '',
            "approved_load.default" => '',
            "issue_date.default" => '',
            "model.default" => '',
            "engine_number.default" => '',
            "address.default" => '',
            "vin.default" => '',
            "register_date.default" => '',
            "appearances.default" => '',
        ]);
        Log::info('驾驶证识别: ' . json_encode($data));
        $data['car_conditions'] = implode('、', $data['car_conditions'] ?? []);
        if ($data['issue_date'] == '1970-01-01') {
            $this->error('驾驶证发证日期被遮挡，请重新上传');
        }
        if ($data['register_date'] == '1970-01-01') {
            $this->error('驾驶证注册日期被遮挡，请重新上传');
        }

        if (!empty($data['appearances'])) {
            $data['appearances'] = json_encode($data['appearances']);
        } else {
            $data['appearances'] = json_encode([]);
        }
        if (empty($data['id'])) {
            $data['id'] = $this->app->db->name($this->table)->insertGetId($data);
            if (!$data['id']) {
                $this->error('添加失败！');
            }
        } else {
            $map = ['uuid' => $this->uuid, 'id' => $data['id']];
            $carInfo = $this->app->db->name($this->table)->where($map)->find();
            if (empty($carInfo)) $this->error('汽车信息不存在！');
            $this->app->db->name($this->table)->where($map)->update($data);
        }

        $nickname = $this->app->db->name('data_user')->where('id', $this->uuid)->value('nickname');
        if ((empty($nickname) || (strpos($nickname, '真惠审') !== false)) && !empty($data['owner'])) {
            $this->app->db->name('data_user')->where('id', $this->uuid)->update(['nickname' => $data['owner']]);
            $cacheKey = config('cacheKey.uid2user') . $this->uuid;
            Cache::delete($cacheKey);
        }

        $this->success('保存成功！', $this->_getCarInfo($data['id']));
    }

    /**
     * 获取车辆
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get()
    {
        $query = $this->_query($this->table)->withoutField('deleted');
        $query->equal('id')->where(['uuid' => $this->uuid, 'deleted' => 0]);
        $result = $query->order('id desc')->page(true, false, false, input('limit', 15));
        foreach ($result['list'] as &$item) {
            if (is_null($item['register_date'])) {
                $item['register_date'] = '';
            } else {
                $item['register_date'] = date('Y-m-d', strtotime($item['register_date']));
            }
            if (is_null($item['issue_date'])) {
                $item['issue_date'] = '';
            } else {
                $item['issue_date'] = date('Y-m-d', strtotime($item['issue_date']));
            }
            if (empty($item['car_conditions'])) {
                $item['car_conditions'] = [];
            } else {
                $item['car_conditions'] = explode('、', $item['car_conditions']);
            }

            if (!empty($item['appearances'])) {
                $item['appearances'] = json_decode($item['appearances'], true);
            } else {
                $item['appearances'] = [];
            }

            // todo 上一次年审的时间
            $item['last_inspection_record'] = '';
        }
        $this->success('获取汽车数据！', $result);
    }

    /**
     * 删除车辆
     * @throws \think\db\exception\DbException
     */
    public function remove()
    {
        $map = $this->_vali([
            'uuid.value' => $this->uuid, 'id.require' => '汽车ID不能为空！',
        ]);
        $carInfo = $this->app->db->name($this->table)->where($map)->find();
        if (empty($carInfo)) $this->error('需要删除的汽车不存在！');
        if ($this->app->db->name($this->table)->where($map)->update(['deleted' => 1]) !== false) {
            $this->success('删除汽车成功！');
        } else {
            $this->error('删除汽车失败！');
        }
    }

    /**
     * 获取指定的汽车
     * @param $id
     * @return null|array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function _getCarInfo($id): ?array
    {
        $map = ['id' => $id, 'uuid' => $this->uuid, 'deleted' => 0];
        return $this->app->db->name($this->table)->withoutField('deleted')->where($map)->find();
    }

}